package cn.jtfadmin.base.shiro.filters;


import cn.jtfadmin.base.lang.common.domain.dto.ResultDTO;
import cn.jtfadmin.base.lang.common.utils.JsonUtils;
import cn.jtfadmin.base.lang.config.statuscode.InvalidUrlStatusCodeConfig;
import cn.jtfadmin.base.shiro.config.ShiroCustomerFilter;
import cn.jtfadmin.base.shiro.config.ShiroWebFilterConfig;
import org.apache.shiro.web.filter.InvalidRequestFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * A request filter that blocks malicious requests. 返回为json 然后格式400, url无效或请求资源不存在
 *
 * <p>
 * This filter checks and blocks the request if the following characters are found in the request URI:
 * <ul>
 * <li>Semicolon - can be disabled by setting {@code blockSemicolon = false}</li>
 * <li>Backslash - can be disabled by setting {@code blockBackslash = false}</li>
 * <li>Non-ASCII characters - can be disabled by setting {@code blockNonAscii = false}, the ability to disable this check will be removed in future version.</li>
 * </ul>
 *
 * @author jtf
 * @see <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/firewall/StrictHttpFirewall.html">This class was inspired by Spring Security StrictHttpFirewall</a>
 * @see ShiroCustomerFilter
 * @see ShiroWebFilterConfig
 * @since 0.0.1
 */
@Component
public class ShiroInvalidFilter implements ShiroCustomerFilter {

    public static final String NAME = DefaultFilter.invalidRequest.name();

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public Filter getFilter() {
        return new InvalidRequestFilter() {
            @Override
            protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
                httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.getOutputStream().write(JsonUtils.toJsonStr(ResultDTO.error(InvalidUrlStatusCodeConfig.InvalidUrl_ERROR, "url无效或请求资源不存在"))
                        .getBytes(StandardCharsets.UTF_8));

                return false;
            }
        };
    }
}
